﻿using Nop.Admin.Models.Directory;
using Nop.Core;
using Nop.Core.Domain.Directory;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
	public class DepartmentController : BaseAdminController
	{
		#region Fields
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IOrganizationService _organizationServce;
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public DepartmentController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IOrganizationService organizationServce,
			IDepartmentService departmentService,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			ICustomerActivityService customerActivityService,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._organizationServce = organizationServce;
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._customerActivityService = customerActivityService;
			this._logger = logger;
		}
		#endregion

		#region Utilities

		[NonAction]
		protected virtual void PrepareAllCategoriesModel(DepartmentModel model)
		{
			if (model == null)
				throw new ArgumentNullException("model");

			model.AvailableDepartments.Add(new SelectListItem
			{
				Text = "无",
				Value = "0"
			});

			var departments = _departmentService.GetAllDepartments(pid: 0);
			foreach (var c in departments)
				model.AvailableDepartments.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() });

		}
		#endregion

		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			var model = new DepartmentListModel();

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult List(DataSourceRequest command, DepartmentListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedKendoGridJson();

			var categories = _departmentService.GetAllDepartments(
				name: model.SearchName,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					var categoryModel = new DepartmentModel
					{
						Id = x.Id,
						Name = x.Name,
						Abbr = x.Abbr,
						IsMaintenance = x.IsMaintenance,
						Active = x.Active,
						PId = x.PId,
						//Breadcrumb = x.GetFormattedBreadCrumb(_departmentService)
					};
					return categoryModel;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}
		#endregion

		#region Create / Edit / Delete

		public virtual ActionResult Create()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			var model = new DepartmentModel
			{
				Active = true,
			};
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Create(DepartmentModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var equipment = new Department
				{
					PId = model.PId,
					Name = model.Name,
					Abbr = model.Abbr,
					IsMaintenance = model.IsMaintenance,
					Active = model.Active,
				};
				_departmentService.InsertDepartment(equipment);

				//activity log
				_customerActivityService.InsertActivity("AddNewEquipment", "新增部门：{0}", equipment.Name);

				SuccessNotification("保存成功");

				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = equipment.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			var equipment = _departmentService.GetDepartmentById(id);
			if (equipment == null || equipment.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new DepartmentModel
			{
				Id = equipment.Id,
				PId = equipment.PId,
				Name = equipment.Name,
				Abbr = equipment.Abbr,
				IsMaintenance = equipment.IsMaintenance,
				Active = equipment.Active,
			};
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(DepartmentModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			var equipment = _departmentService.GetDepartmentById(model.Id);
			if (equipment == null || equipment.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			if (ModelState.IsValid)
			{
				equipment.PId = model.PId;
				equipment.Name = model.Name;
				equipment.Abbr = model.Abbr;
				equipment.IsMaintenance = model.IsMaintenance;
				equipment.Active = model.Active;
				equipment.Name = model.Name;
				_departmentService.UpdateDepartment(equipment);

				//activity log
				_customerActivityService.InsertActivity("EditEquipment", "编辑部门：{0}", equipment.Name);

				SuccessNotification("保存成功");
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = equipment.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllCategoriesModel(model);

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageDepartments))
				return AccessDeniedView();

			var equipment = _departmentService.GetDepartmentById(id);
			if (equipment == null)
				//No equipment found with the specified id
				return RedirectToAction("List");

			_departmentService.DeleteDepartment(equipment);

			//activity log
			_customerActivityService.InsertActivity("DeleteEquipment", "删除部门：{0}", equipment.Name);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}


		#endregion
	}
}